package handler

import (
	"fmt"
	"github.com/valyala/fasthttp"
	"kop/modules/pay/handler/baowan"
	"kop/modules/pay/handler/chuangku"
	"kop/util/log"
	"net/http"
	"strings"
)

// recover
func rec(ctx *fasthttp.RequestCtx) {

	if r := recover(); r != nil {

		var err error

		switch e := r.(type) {
		case error:
			err = e
		case string:
			err = fmt.Errorf(e)
		default:
			err = fmt.Errorf("%v", e)
		}

		ctx.Error(err.Error(), http.StatusInternalServerError)

		log.Error("RPC [%s] Error: %s", ctx.Path(), err.Error())
	}
}

func Handler(ctx *fasthttp.RequestCtx) {

	defer rec(ctx)

	var path = string(ctx.Path())

	switch path {
	case "/callback/chuangku":

		var res chuangku.Res

		if err := chuangku.Handler(ctx); err != nil {
			_, _ = fmt.Fprintf(ctx, res.Err(err.Error()))
		} else {
			_, _ = fmt.Fprintf(ctx, res.Ok())
		}

	default:

		var paths = strings.Split(path, "/")
		if paths[1] == "callback" && paths[2] == "baowan" {

			var res baowan.Res

			if err := baowan.Handler(ctx); err != nil {
				_, _ = fmt.Fprintf(ctx, res.Err(err.Error()))
			} else {
				_, _ = fmt.Fprintf(ctx, res.Ok())
			}
		}

	}

	log.Info("Request [%s] Success", ctx.Path())
}
